$(function () {
	
    
    $("#jqGrid").jqGrid({
    	
    	url: baseURL+"user/list",
        datatype: "json",
        colModel: [
			{ label: '手机号', name: 'phone', sortable:false, width: 46, formatter: function(value, options, row)
				{
				if(null == value || undefined == value) return "";
				return "<a href='detail.html?id=" + row.id+"&phone="+ row.phone + "'>" + value +  "</a>";
			}
			},
			/*{ label: '真实姓名', name: 'realName', sortable:false, width: 80 },
			{ label: '身份证号', name: 'identCode', sortable:false, width: 80 },*/
			/*{ label: '昵称', name: 'nickName', sortable:false, width: 58 },*/
			/*{ label: '性别', name: 'gender', width: 80, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">女</span>' : 
					'<span class="label label-success">男</span>';
			}},
			{ label: '家庭地址', name: 'address', sortable:false, width: 80 },*/
			{ label: '状态', name: 'state', width: 36, formatter: function(value, options, row){
				if(value && value === 1){
					if(hasPermission("user:lock")) {
                        return "<a href='javascript:vm.lock(" + row.id + "," + row.state + ",\""+row.phone+"\");'><span class='label label-success'><i class='fa fa-unlock'></i>可用</span></a>";
                    }
					return "<span class='label label-success'><i class='fa fa-unlock'></i>可用</span>";
				}
				if(hasPermission("user:lock")) {
                    return "<a href='javascript:vm.lock(" + row.id + "," + row.state + ",\""+row.phone+"\");'><span class='label label-danger'><i class='fa fa-lock'></i>禁用</span></a>";
                }
				return "<span class='label label-danger'><i class='fa fa-lock'></i>禁用</span>";
			}},
            { label: '转账', name: 'statetrans', width: 36, formatter: function(value, options, row){
            	if(value && value === 1){
					if(hasPermission("user:locktrans")) {
                        return "<a href='javascript:vm.lockTran(" + row.id + "," + row.statetrans + ",\""+row.phone+"\");'><span class='label label-success'><i class='fa fa-unlock'></i>可用</span></a>";
                    }
					return "<span class='label label-success'><i class='fa fa-unlock'></i>可用</span>";
				}
				if(hasPermission("user:locktrans")) {
                    return "<a href='javascript:vm.lockTran(" + row.id + "," + row.statetrans + ",\""+row.phone+"\");'><span class='label label-danger'><i class='fa fa-lock'></i>禁用</span></a>";
                }
				return "<span class='label label-danger'><i class='fa fa-lock'></i>禁用</span>";
            }},
			{ label: '创建时间', name: 'timeCreate', sortable:false, width: 60 },
			{ label: '操作', name: 'operation', sortable:false, width: 96, formatter: function(value, options, row)
				{
					var ret = "";
					if(hasPermission("ymbdetail:charge")){
						ret  += "<a href='javascript:vm.charge(" + row.id +",\""+row.phone+"\");'><span class='label label-primary'><i class='fa fa-bitcoin'></i>充值YMB</span></a>&nbsp;&nbsp;"
					}
                    if(hasPermission("user:concatPhone")){
                        ret  += "<a href='javascript:vm.concatPhone(" + row.id +",\""+row.phone+"\");'><span class='label label-primary'><i class='fa fa-phone'></i>短信手机</span></a>&nbsp;&nbsp;"
                    }
                    if(hasPermission("fundmergedetail:mergeFund")){
                        ret  += "<a href='javascript:vm.mergeFund(" + row.id +",\""+row.phone+"\");'><span class='label label-primary'><i class='fa fa-rmb'></i>合并资金</span></a>&nbsp;&nbsp;"
                    }
                    ret  += "<a href='./detail.html?id=" + row.id+"&phone="+ row.phone + "'><span class='label label-primary'><i class='fa fa-info-circle'></i>详情</span></a>";
                    return ret;
				}
			}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 20,
		rowList : [10,20,30,50,100,200],
        rownumbers: false, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total",
           	
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order",
            
        },
        
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        	
        }
    });
    jQuery("#jqGrid").jqGrid('navGrid','#jqGrid',{edit:false,add:false,del:false});
    
    //过滤时间
    var rangetime = $('#filterTime').daterangepicker({
        autoApply:false,
        singleDatePicker:false,
        showDropdowns:true,         // 是否显示年月选择条件
    	timePicker: true, 			// 是否显示小时和分钟选择条件
    	timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        timePicker24Hour : true,
        opens : 'left', //日期选择框的弹出位置
        startDate: moment().startOf('year'), //startDate和endDate 的值如果跟 ranges 的两个相同则自动选择ranges中的行. 这里选中了清空行
        endDate: moment().endOf('year'),
    	ranges: {
    		'今日': [moment().startOf('day'), moment().endOf('day')],
    		'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
    		'最近7日': [moment().subtract(6, 'days'), moment()],
    		'最近30日': [moment().subtract(29, 'days'), moment()],
    		'本月': [moment().startOf('month'), moment().endOf('month')],
    		'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
    		'本年': [moment().startOf('year'), moment().endOf('year')],
    		'去年': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
    	},
        locale : {
            //format: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm',
            separator : ' - ',
        	customRangeLabel : '自定义',
            applyLabel : '确定',
            cancelLabel : '取消',
            fromLabel : '起始时间',
            toLabel : '结束时间',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1,
            startDate: moment().startOf('day'),
            endDate: moment().endOf('day')
        }
    },
    function(start, end, label) // 格式化日期显示框
    {
    	//选择时间 回调，暂时不做操作。。。
        $('#filterTime').val(start.format('YYYY-MM-DD HH:mm') + " - " + end.format('YYYY-MM-DD HH:mm'));
    });
    
    $('#filterTime').val('');
    setTimeout("$('#filterTime').val('')", 100);
    
    new AjaxUpload('#upload', {
        action: baseURL + 'user/imports?token=' + token,
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
        	if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
                alert('只支持xls、xlsx、格式的文件！');
                return false;
            }
        	$(window.parent.document).find("#overlay").show();
        	$("#light").show();
        },
        onComplete : function(file, r){
            if(r.code == 0){
            	$(window.parent.document).find("#overlay").hide();
            	$("#light").hide();
                vm.reload();
            }else{
            	$(window.parent.document).find("#overlay").hide();
            	$("#light").hide();
                alert(r.msg,function(){
                	 //vm.reload();
                	window.location.reload();
                });
               
            }
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			key: null
		},
		showList: true,
		title: null,
		dto: {}
	},
	methods: {
		query: function () {

			vm.reload();
			
			
		},
		trash: function () {
			$('#filterTime').val('');
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dto = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改手机号";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.dto.id == null ? baseURL + "user/save" : baseURL + "user/update";
			console.log(JSON.stringify(vm.dto));
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.dto),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
							
						});
								
					}else{
						alert(r.msg);
					}
				}
			});
		},
		delCol: function (id) {
			if(id == null){
				return ;
			}
			var ids = [id];
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "user/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		lock: function (id,state,phone) {
			if(id == null || state == null){
				return ;
			}

            vm.title = "更改用户状态";
            vm.dto = {id : id,userPhone : phone};
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                title: "更改用户状态",
                area: ['588px', '300px'],
                shadeClose: true,
                anim: 1, //动画类型
                shade: 0.01 ,//遮罩透明度
                content: jQuery("#alertUserState"),
                btn: ['确定','取消'],
                btn1: function (index)
                {
                    var remark =vm.dto.address;
                	if(state==1){//锁定时将状态改成相反的状态
                        if(null==remark||remark.replace(/(^\s*)|(\s*$)/g, "")==""){
                            alert("禁用操作备注不能为空");
                            return false;
                        }
                        state=0;
                    }else {
                        state=1;
                    }
                        var params = {};
                        params.id=id;
                        params.state=state;
                        params.phone=phone;
                        params.address=vm.dto.address;


                    confirm('确定后将无法修改，请谨慎操作？', function(){
                            $.ajax({
                                type: "PUT",
                                url: baseURL + "user/lock",
                                data: JSON.stringify(params),
                                success: function(r){
                                    if(r.code === 0){
                                        layer.close(index);
                                        alert('操作成功', function(index){
                                            $("#jqGrid").trigger("reloadGrid");
                                        });
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        });
                }
            });



		},
        lockTran: function (id,statetrans,phone) {
            if(id == null || statetrans == null){
                return ;
            }

            vm.title = "更改用户转账状态";
            vm.dto = {id : id,statetrans : statetrans,userPhone : phone};
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                title: "更改用户状态",
                area: ['588px', '300px'],
                shadeClose: true,
                anim: 1, //动画类型
                shade: 0.01 ,//遮罩透明度
                content: jQuery("#alertUserState"),
                btn: ['确定','取消'],
                btn1: function (index)
                {
                    var remark=vm.dto.address;
                    if(statetrans==1){//锁定时将状态改成相反的状态
                        if(null==remark||remark.replace(/(^\s*)|(\s*$)/g, "")==""){
                            alert("禁用操作备注不能为空");
                            return false;
                        }
                        statetrans=0;
                    }else {
                        statetrans=1;
                    }
                    var params = {};
                    params.id=id;
                    params.statetrans=statetrans;
                    params.phone=phone;
                    params.address=vm.dto.address;
                    confirm('确定后将无法修改，请谨慎操作？', function(){
                        $.ajax({
                            type: "PUT",
                            url: baseURL + "user/locktrans",
                            data: JSON.stringify(params),
                            success: function(r){
                                if(r.code === 0){
                                    layer.close(index);
                                    alert('操作成功', function(index){
                                        $("#jqGrid").trigger("reloadGrid");
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    });
                }
            });





        },
        charge: function (id, phone) {
			if(id == null) return;
			
            vm.title = "充值YMB";
			vm.dto = {'userId' : id, 'phone' : phone};
			
			layer.open({
				type: 1,
				skin: 'layui-layer-rim',
				title: "充值YMB",
				area: ['588px', '386px'],
				shadeClose: true,
				anim: 1, //动画类型
				shade: 0.01 ,//遮罩透明度
				content: jQuery("#chargeLayer"),
				btn: ['确定','取消'],
				btn1: function (index) 
				{
					var data = {userId:id, phone:phone, money:vm.dto.money, description:vm.dto.description};
					confirm('确定要给用户' + phone + '充值易买宝？', function(){
						$.ajax({
							type: "PUT",
						    async:false,
						    url: baseURL + "ymbdetail/charge",
			                contentType: "application/json",
						    data: JSON.stringify(data),
						    success: function(r){
								if(r.code == 0){
									layer.close(index);
									alert('操作成功', function(index){
										//vm.reload();
									});
								}else{
									alert(r.msg);
								}
							}
						});
					});
	            }
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "user/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
							
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "user/info/"+id, function(r){
                vm.dto = r.dto;
            });
		},
        concatPhone : function(id,phone){ //关联接受短信的手机号码
            if(id == null) return;

            vm.title = "短信手机号码";
            vm.dto = {id : id,userPhone : phone };
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                title: "短信手机号码",
                area: ['588px', '300px'],
                shadeClose: true,
                anim: 1, //动画类型
                shade: 0.01 ,//遮罩透明度
                content: jQuery("#concatPhone"),
                btn: ['确定','取消'],
                btn1: function (index)
                {
                	if($.trim(vm.dto.interPhone) == null || $.trim(vm.dto.interPhone) == ''){
                		alert("短信手机号码不允许为空");
                		return;
					}
                    if($.trim(vm.dto.interPhone) == phone){
                        alert("原手机号码和短信手机号码不能一样");
                        return;
					}
                    var data = {id:id, phone:phone,address:vm.dto.address, interPhone : vm.dto.interPhone};
                    confirm('确定将短信手机号码更改为' + vm.dto.interPhone + '？', function(){
                        $.ajax({
                            type: "PUT",
                            url: baseURL + "user/concatPhone",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            success: function(r){
                                if(r.code == 0){
                                    layer.close(index);
                                    alert('操作成功', function(index){
                                        //vm.reload();
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    });

                }
            });
		},
        mergeFund : function(id,payPhone){ //合并账号资金
            if(id == null || payPhone == null) return;
            vm.title = "合并资金";
            vm.dto = {id : id,payPhone : payPhone};
            layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                title: "合并资金",
                area: ['588px', '300px'],
                shadeClose: true,
                anim: 1, //动画类型
                shade: 0.01 ,//遮罩透明度
                content: jQuery("#mergeFund"),
                btn: ['确定','取消'],
                btn1: function (index)
                {
                	if($.trim(vm.dto.recPhone) == null || $.trim(vm.dto.recPhone)  == ""){
                		alert("目标账号不能为空");
                		return;
					}
					if(payPhone == $.trim(vm.dto.recPhone)){
                        alert("原手机和目的手机号不能相同");
                        return;
					}
                    confirm('确定将账号' + payPhone + '合并到 ' + vm.dto.recPhone + '？', function(){
                        var data = {payUserId:id, payPhone:payPhone,remark:vm.dto.remark,recPhone : vm.dto.recPhone};
                        $.ajax({
                            type: "PUT",
                            url: baseURL + "fundmergedetail/mergeFund",
                            contentType: "application/json",
							async : false,
                            data: JSON.stringify(data),
                            success: function(r){
                                if(r.code == 0){
                                    layer.close(index);
                                    alert('操作成功', function(index){
                                        //vm.reload();
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    });

                }
            });
        },
		reload: function (event) {
			vm.showList = true;
			var _postData = $("#jqGrid").jqGrid('getGridParam','postData');
			delete _postData['sts'];
			delete _postData['ets'];
			delete _postData['p'];
			
			_postData['p'] = $("#phoneNumber").val();
			if((vtime = $.trim($('#filterTime').val())) != '')
			{
				if(vtime.indexOf(" - ") > -1)
				{
					_postData['sts'] = ($.trim(vtime.split(" - ")[0]) + ":00");
					_postData['ets'] = ($.trim(vtime.split(" - ")[1]) + ":59");
				}
				else
				{
					_postData['sts'] = getTime(vtime);
				}
			}

			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
	}
	
});
